package com.itheima.tliaswebmanagement.filter;

import com.itheima.tliaswebmanagement.pojo.vo.LoginInfo;
import com.itheima.tliaswebmanagement.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import javax.print.DocFlavor;
import java.io.IOException;

/**
 * @Description LoginCheckFilter
 * @Author ziguan ling
 * @Date 2025--01--11
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求url
        // ----------将父接口转换为功能更强的子接口
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse  response = (HttpServletResponse)servletResponse;

        //-----------获取当前请求路径
        String path = request.getRequestURI();

        // 判断请求url中是否包含login,如果包含,说明是登录操作,放行
        if(path.contains("/login")){
            filterChain.doFilter(request, response);
            return;
        }

        // 获取请求头中的令牌
        String token = request.getHeader("token");

        // 判断令牌是否存在,如果不存在,响应401
        if(token == null || token.equals("")){
            response.setStatus(401);
            return;
        }

        // 解析token,如果解析失败,响应401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            log.info("员工id: {}登陆验证成功了", id);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return;
        }

        // 放行
        filterChain.doFilter(request, response);
    }
}












